<template>
  <div>
    <tool-bar
      @select:emoji="handleSelectEmoji"
      @upload:picture="handleUpload"
    />
    <div id="messageEditor">
      <el-scrollbar max-height="100" re="scrollbarRef">
        <div ref="chatElm" class="message-input"></div>
      </el-scrollbar>
      <div class="message-send">
        <el-space>
          <el-text style="color: #999999">按enter发送</el-text>
          <el-button
            :disabled="sendDisabled"
            size="small"
            type="primary"
            @click="sendMsg"
            >发送(S)
          </el-button>
        </el-space>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {
  defineEmits,
  defineProps,
  onMounted,
  onUnmounted,
  ref,
  watch,
} from "vue";
import ChatArea from "chatarea";
import "chatarea/lib/ChatArea.css";
import ToolBar from "@/components/chat/ToolBar.vue";
import { ElScrollbar } from "element-plus";

const chat = ref<ChatArea<any>>();
const chatElm = ref();
// 初始化实例对象
const initChat = () => {
  chat.value = new ChatArea<any>({
    copyType: ["text"],
    elm: chatElm?.value,
    placeholder: "请输入",
  });

  // 绑定键盘发送事件
  chat.value.addEventListener("enterSend", sendMsg);
  chat.value.addEventListener("operate", onOperate);
};

//输入框改变事件
const sendDisabled = ref(false);
ref<InstanceType<typeof ElScrollbar>>();
const onOperate = () => {
  sendDisabled.value = chat.value?.isEmpty(true) as boolean;
};
// 定义发送消息方法
const emit = defineEmits(["send:message"]);
const sendMsg = async () => {
  // 空内容拦截
  if (!chat.value || chat.value.isEmpty(true)) {
    return;
  }
  emit("send:message", chat.value?.getText());
  chat.value?.clear();
};
//上传图片
const handleUpload = (url: string) => {
  emit("send:message", url, "image");
};

//选择emoji
function handleSelectEmoji(em: any) {
  chat.value?.insertText(em);
}

const props = defineProps({
  text: {
    type: String,
    default: "",
  },
});
watch(
  () => props.text,
  () => {
    if (chat.value) {
      chat.value?.insertText(props.text);
    }
  }
);
onMounted(() => {
  initChat();
});
onUnmounted(() => {
  chat.value && chat.value.dispose();
});
</script>

<style scoped>
#messageEditor {
  height: 120px;
  display: flex;
  flex-direction: column;
  position: relative;

  .message-input {
    flex: 1;

    :deep(.chat-placeholder-wrap) {
      color: #ccc;
      font-style: normal;
    }
  }

  .message-send {
    margin-top: 5px;
    height: 20px;
    line-height: 20px;
    width: 30%;
    right: 30px;
    bottom: -10px;

    position: absolute;

    display: flex;
    justify-content: end;
  }
}
</style>
